package org.kyw.basic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.kyw.basic.constant.LoginConstant;
import org.kyw.basic.dto.LoginDto;
import org.kyw.basic.exception.BusinessException;
import org.kyw.basic.service.ILoginService;
import org.kyw.basic.util.AjaxResult;
import org.kyw.basic.util.HttpClientUtils;
import org.kyw.basic.util.MD5Utils;
import org.kyw.basic.util.StrUtils;
import org.kyw.user.domain.Logininfo;
import org.kyw.user.domain.User;
import org.kyw.user.domain.WxUser;
import org.kyw.user.mapper.LogininfoMapper;
import org.kyw.user.mapper.UserMapper;
import org.kyw.user.mapper.WxUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> account(LoginDto dto) {
        if(StringUtils.isEmpty(dto.getUsername())
                || StringUtils.isEmpty(dto.getPassword())
                || StringUtils.isEmpty(dto.getType())) {
            throw new BusinessException("必要信息不能为空");
        }

        Logininfo logininfo = logininfoMapper.loadByDto(dto);

        if (logininfo == null){
            throw new BusinessException("用户名或密码错误");
        }

        String salt = logininfo.getSalt();

        String md5Password = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        if(!md5Password.equals(logininfo.getPassword())){
            throw new BusinessException("用户名或密码错误");
        }
        return doLogin(logininfo);
    }

    @Override
    public AjaxResult wechat(Map<String, String> param) {
        String code = param.get("code");
        if(!StringUtils.hasLength(code)){
            throw new BusinessException("参数异常");
        }
        String getTokenUrl = LoginConstant.GET_ACCESS_TOKEN
                .replace("APPID", LoginConstant.APPID)
                .replace("SECRET", LoginConstant.SECRET)
                .replace("CODE", code);
        String tokenStr = HttpClientUtils.httpGet(getTokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(tokenStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");

        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        if(wxUser != null && wxUser.getUser_id() != null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxUser.getUser_id());
            Map<String, Object> map = doLogin(logininfo);
            return AjaxResult.me().setResultObj(map);
        }else {
            String bindParam = "accessToken=" + accessToken + "&openId=" + openId;
            return AjaxResult.me().setSuccess(false).setResultObj(bindParam);
        }

    }

    @Override
    public Map<String, Object> binder(Map<String, String> param) {
        String phone = param.get("phone");
        String verifyCode = param.get("verifyCode");
        String accessToken = param.get("accessToken");
        String openId = param.get("openId");

        if(StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)) {
            throw new BusinessException("参数有问题");
        }

        Object codeTmp = redisTemplate.opsForValue().get(LoginConstant.PHONE_BINDER + phone);

        if(codeTmp == null) {
            throw new BusinessException("验证码已失效，请重新获取");
        }

        String code = codeTmp.toString().split(":")[0];
        if(!verifyCode.equalsIgnoreCase(code)) {
            throw new BusinessException("验证码输入错误");
        }

        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo = null;
        if(user != null){
            logininfo = logininfoMapper.loadById(user.getLogininfo_id());
        }else {
            user = initUser(phone);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }

        String getWxUserInfoUrl = LoginConstant.WXUSER_INFO_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserInfoStr = HttpClientUtils.httpGet(getWxUserInfoUrl);
        WxUser wxUser = JSONObject.parseObject(wxUserInfoStr, WxUser.class);
        wxUser.setUser_id(user.getId());
        wxUserMapper.save(wxUser);

        Map<String, Object> map = doLogin(logininfo);

        return map;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPassword(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String md5Password = MD5Utils.encrypByMd5("1" + salt);
        user.setSalt(salt);
        user.setPassword(md5Password);
        return user;
    }

    /**
     * 完成登录
     * @param logininfo
     * @return
     */
    public Map<String, Object> doLogin(Logininfo logininfo){
        //生成token随机串
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
        );
        //返回token + logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);
        return map;
    }
}
